﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxLeaf.Platform.DataContract;
using CommonsLib.DB;
using MaxLeaf.Platform.DALImplementation;
using MaxLeaf.Platform.Functions;
using CommonsLib.Utility;
using MaxLeaf.Platform.Commons;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;

namespace MaxLeaf.Platform.BLLImplementation
{
    public class SCPCategoryBLL:BaseBLL
    {
     
        public override string FinterIDFields
        {
            get
            {
                return string.Format("{0},{1}", "FInterID", (int)FinterIDType.Category);
            }
        }
        protected override void Add_BeforeValid(DBAccess dbcon, object model)
        {
             InitSCPCategorySeqNo(dbcon, model);
        }

        protected override void Update_BeforeValid(DBAccess dbcon, object model)
        {
             InitSCPCategorySeqNo(dbcon, model);
        }

        private void InitSCPCategorySeqNo(DBAccess dbcon, object model)
        {
            SCPCategoryDataModel scp = (SCPCategoryDataModel)model;
            if (scp.SCPCategorySeqNo == 0)
            {
                scp.SCPCategorySeqNo = ((SCPCategoryDAL)this.CurrentDAL).GetNextSCPCategorySeqNo(dbcon, scp);
            }

            
        }


        internal SCPCategoryDataModel GetSCPCategory(int intUserID, int intGoodsID, bool blnTop)
        {
            using (DBAccess dbcon = DataFunc.GetDBAccessByDataModelType(typeof(SCPCategoryDataModel)))
            {

                SCPCategoryDataModel model = new SCPCategoryDataModel();
                using (DbDataReader rdr = ((SCPCategoryDAL)this.CurrentDAL).GetSCPCategory(dbcon, intUserID, intGoodsID, blnTop)
                   )
                {
                    if (rdr.Read())
                    {
                        
                        DataFunc.Read(model, rdr, true);
                        
                    }
                }

                //if (blnTop)
                //{
                //    while (model.ForeignKey > 0)
                //    {
                //        model = (SCPCategoryDataModel)Select(model, model.ForeignKey);
                //    }

                //}
                return model;
                

            }
        }


        public override object Add(object model)
        {

            using (System.Transactions.TransactionScope ts = DataFunc.CreateTransactionScope())
            {
                
                object obj = base.Add(model);

                using (DBAccess dbcon = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPBase)))
                {
                    SCPCategoryDataModel data = (SCPCategoryDataModel)model;
                    AddChild(dbcon, data);


                }

                ts.Complete();

                return obj;
            }
        }

        public override object Update(object model)
        {

            using (System.Transactions.TransactionScope ts = DataFunc.CreateTransactionScope())
            {
                using (DBAccess dbcon = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPBase)))
                {
                    SCPCategoryDataModel data = (SCPCategoryDataModel)model;
                    SCPCategoryDataModel olddata = (SCPCategoryDataModel)Select(new SCPCategoryDataModel(), data.Key);
                    if (olddata==null  || data.CompanyID != olddata.CompanyID)
                    {
                        DeleteChild(dbcon, olddata);
                        AddChild(dbcon, data);
                    }
                    else
                    {
                        UpdateChild(dbcon, olddata, data);
                    }


                }
                object obj = base.Update(model);
                ts.Complete();

                return obj;
            }
        }

        private void UpdateChild(DBAccess dbcon, SCPCategoryDataModel oldparentData, SCPCategoryDataModel parentData)
        {
            DataTable dt = GetChildCompany(dbcon, oldparentData.Key);
            foreach (DataRow dr in dt.Rows)
            {
                bool blnUpdate = false;
                foreach (SCPCategoryDataModel child in SelectByCond(new SCPCategoryDataModel()
                    , new List<AddInfo>() { 
                                new AddInfo{ Name= AddInfoType.Cond ,Value= new List<Cond>() { 
                                        new Cond { PropName ="SCPCategorySeqNo", Compare = CompareType.Equal, Value = oldparentData.SCPCategorySeqNo }
                                        ,new Cond { PropName ="CompanyID", Compare = CompareType.Equal, Value =CvtFunc.ToInt(dr["CompanyID"]) }
                                    }
                                } 
                            }
                ).Data)
                {
                    blnUpdate = true;

                    child.SCPCategorySeqNo = parentData.SCPCategorySeqNo;
                    child.Name = parentData.Name;
                    child.num = parentData.num;
                    child.info = parentData.info;
                    child.ParentSCPCategorySeqNo = parentData.ParentSCPCategorySeqNo;
                    child.sys = parentData.sys;
                    child.Void = parentData.Void;

                    base.Update(child);
                }
                if (!blnUpdate)
                {
                    AddChild(dbcon, parentData);
                }
            }
        }

        private void AddChild(DBAccess dbcon, SCPCategoryDataModel parentData)
        {
            DataTable dt = GetChildCompany(dbcon, parentData.Key);
            foreach (DataRow dr in dt.Rows)
            {
                SCPCategoryDataModel child = new SCPCategoryDataModel
                {

                };
                child.CompanyID = CvtFunc.ToInt(dr["CompanyID"]);
                child.SCPCategorySeqNo = parentData.SCPCategorySeqNo;
                child.Name = parentData.Name;
                child.num = parentData.num;
                child.info = parentData.info;
                child.ParentSCPCategorySeqNo = parentData.ParentSCPCategorySeqNo;
                child.sys = parentData.sys;
                child.Void = parentData.Void;
                if (parentData.ParentSCPCategorySeqNo == 0)
                {
                    child.Is_Display = false;
                }
                base.Add(child);

            }
        }

        public override bool Delete(object model)
        {

            using (System.Transactions.TransactionScope ts = DataFunc.CreateTransactionScope())
            {
                using (DBAccess dbcon = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPBase)))
                {
                    DeleteChild(dbcon, (SCPCategoryDataModel)model);
                }
                bool blnRT = base.Delete(model);
                ts.Complete();

                return blnRT;
            }
        }

        private void DeleteChild(DBAccess dbcon, SCPCategoryDataModel parentData)
        {
            DataTable dt = GetChildCompany(dbcon, parentData.Key);
            foreach (DataRow dr in dt.Rows)
            {
                foreach (SCPCategoryDataModel child in SelectByCond(new SCPCategoryDataModel()
                    , new List<AddInfo>() { 
                                new AddInfo{ Name= AddInfoType.Cond ,Value= new List<Cond>() { 
                                        new Cond { PropName ="SCPCategorySeqNo", Compare = CompareType.Equal, Value = parentData.SCPCategorySeqNo }
                                        ,new Cond { PropName ="CompanyID", Compare = CompareType.Equal, Value =CvtFunc.ToInt(dr["CompanyID"]) }
                                    }
                                } 
                            }
                ).Data)
                {
                    base.Delete(child);
                }
            }
        }

        private DataTable GetChildCompany(DBAccess dbcon, int intKey)
        {
            string strSql = @"select distinct a.CompanyID from mCompany a  inner join  SCPCategory b  
                        on  dbo.F_GetParentCompanyID(a.CompanyID)=b.CompanyID and b.CompanyID<>0 
                        where b.FinterID=@Key";
            DataTable dt = dbcon.GetDataTable(strSql, new SqlParameter[]{
                        new SqlParameter("@Key",intKey.ToString())                        
                    });
            return dt;
        }
    }
}
